from django.conf import settings
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import check_encrypted_openid
from users.models import User


class QQUserSerializer(serializers.Serializer):
    mobile = serializers.CharField(label='手机号', write_only=True)
    password = serializers.CharField(label='密码', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    openid = serializers.CharField(label='openid', write_only=True)

    def validate(self, attrs):
        # 校验openid是否还有效
        encrypted_openid = attrs.get('openid')
        openid = check_encrypted_openid(encrypted_openid)
        if not openid:
            # 无效
            raise serializers.ValidationError('openid无效')

        attrs['openid'] = openid
        # 有效 判断短信验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code =  redis_conn.get('sms_%s' % mobile)
        if not real_sms_code:
            # 验证码无效
            raise serializers.ValidationError('无效的短信验证码')
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('验证码错误')
        # 验证码正确 继续验证用户是否存在
        user = User.objects.get(mobile=mobile)
        if user:
            # 验证密码
            password = attrs.get('password')
            if not user.check_password(password):
                # 密码错误
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
            return attrs

    def create(self, validated_data):
        user = validated_data.get('user')
        if not user:
            # 用户不存在
            mobile = validated_data.get('mobile')
            password = validated_data.get('password')
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )

        # 绑定
        openid = validated_data.get('openid')
        OAuthQQUser.objects.create(
            openid=openid,
            user=user
        )

        return user
